<?php

namespace App\Http\Rest\Demo;

use App\Common\Rest\RestHelper;
use App\Http\Index\Rest\DbRest;
use Framework\Foundation\Rest\ResourceConverter;
use Framework\Foundation\Rest\RestRequestInfo;
use Framework\Foundation\Warehouse;
use Psr\Http\Message\ServerRequestInterface;

class RestControl
{
    public function index($params, ServerRequestInterface $request)
    {
        /**
         * @var $restRequestInfo RestRequestInfo;
         */
        $restRequestInfo = $request->getAttribute('restRequestInfo');
        $targetInfo = $this->mapResource($restRequestInfo->getRestTargetInfo());

        $className = "\App\Http\Rest\Demo\Resources\\" . $targetInfo['object'];
        if (class_exists($className)) {
            $obj = new $className;
        } else {
            $obj = new \App\Http\Rest\Demo\DbResource;
        }

        echo '<pre>';
        print_r(Warehouse::instance('frame'));
        exit('</pre>');
        
        return call_user_func([$obj, $targetInfo['action']], $targetInfo, $request);
    }

    public function mapResource($targetInfo)
    {
        $map = [
        ];

        if (isset($map[$targetInfo['resource']])) {
            $targetInfo['resource'] = $map[$targetInfo['resource']];
        }

        return $targetInfo;
    }

    public function checkPublicAllow($route)
    {
        $indexRest = include ROOT . '/app/conf/index_rest.php';
        if (key_exists($route['target'], $indexRest['public_allow'])
            && in_array($route['method'], $indexRest['public_allow'][$route['target']])) {
            return true;
        }

        return false;
    }
}
